package top.taooc.example.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import top.taooc.example.common.model.User;
import top.taooc.example.common.service.UserService;
import top.taooc.model.RpcRequest;
import top.taooc.model.RpcResponse;
import top.taooc.serializer.JdkSerializer;

import java.io.IOException;

/**
 * @author songtao@guishangyi.cn
 * @date 2024年06月27日 10:43:07
 * @packageName top.taooc.example.consumer
 * @className UserServiceProxy
 * @Menu 静态代理
 */
public class UserServiceProxy implements UserService {

    /**
     * 获取用户
     *
     * @param user
     */
    @Override
    public User getUser(User user) {
        //指定序列化器
        JdkSerializer serializer = new JdkSerializer();
        //发请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .paramterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        try {
            byte[] bodyBytes = serializer.seriailize(rpcRequest);
            byte[] result;
            try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(bodyBytes)
                    .execute()){
                result = httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User) rpcResponse.getData();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
